package com.hitqz.robot.biz.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hitqz.robot.api.business.enums.FormConfigEnum;
import com.hitqz.robot.api.business.model.param.base.QueryPageParams;
import com.hitqz.robot.api.business.model.param.form.QueryFormFieldParams;
import com.hitqz.robot.api.business.model.vo.form.FormConfigModalVo;
import com.hitqz.robot.api.business.model.vo.form.FormConfigNameOptionVo;
import com.hitqz.robot.api.common.entity.FormConfig;
import com.hitqz.robot.api.common.entity.FormFieldConfig;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.biz.service.FormConfigService;
import com.hitqz.robot.biz.service.FormFieldConfigService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 动态表单管理
 * @author wengyx
 * @date 2024/9/18
 */
@RestController
@AllArgsConstructor
@RequestMapping("/form")
@Tag(name = "表单管理")
@Slf4j
public class FormConfigController {

    private final FormConfigService formConfigService;
    
    private final FormFieldConfigService formFieldConfigService;

    private final RobotService robotService;


    @GetMapping("/title")
    @Operation(summary = "获取表单名称选项")
    public R<List<FormConfigNameOptionVo>> titleOption() {
        ArrayList<FormConfigNameOptionVo> list = new ArrayList<>();
        for (FormConfigEnum formConfigEnum : FormConfigEnum.values()) {
            FormConfigNameOptionVo dto = new FormConfigNameOptionVo();
            dto.setFormName(formConfigEnum.getFormName());
            dto.setFormTitle(formConfigEnum.getFormTitle());
            list.add(dto);
        }
        return R.ok(list);
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询表单")
    public R<Page<FormConfig>> page(QueryPageParams query) {
        Page page = new Page<>(query.getCurrent(),query.getSize());
        Page<FormConfig> data = formConfigService.page(page,
                Wrappers.<FormConfig>lambdaQuery()
                        .orderByDesc(FormConfig::getId));
        return R.ok(data);
    }

    @GetMapping("{formId}")
    @Operation(summary = "根据id查询表单")
    public R<FormConfig> getById(@PathVariable("formId") Integer id) {
        FormConfig formConfig = formConfigService.getById(id);
        return R.ok(formConfig);
    }

    @PostMapping
    @Operation(summary = "新增表单")
    public R save(@RequestBody @Validated FormConfig dto){
        formConfigService.save(dto);
        return R.ok();
    }

    @PutMapping
    @Operation(summary = "修改表单")
    public R updateById(@RequestBody @Validated FormConfig dto) {
        return R.ok(formConfigService.updateById(dto));
    }

    @DeleteMapping
    @Operation(summary = "根据id删除表单")
    public R removeById(@RequestBody Integer[] ids) {
        if (formConfigService.removeBatchByIds(CollUtil.toList(ids))) {
            formFieldConfigService.remove(Wrappers.<FormFieldConfig>lambdaQuery().in(FormFieldConfig::getFormId, CollUtil.toList(ids)));
        }
        return R.ok();
    }

    @PostMapping("/field/page")
    @Operation(summary = "分页查询表单字段")
    public R<Page<FormFieldConfig>> fieldPage(@RequestBody QueryFormFieldParams query) {
        Page page = new Page<>(query.getCurrent(),query.getSize());
        Page<FormFieldConfig> data = formFieldConfigService.page(page,
                Wrappers.<FormFieldConfig>lambdaQuery()
                        .eq(query.getFormId()!=null,FormFieldConfig::getFormId,query.getFormId())
                        .orderByDesc(FormFieldConfig::getId));
        return R.ok(data);
    }

    @GetMapping("/field/{fieldId}")
    @Operation(summary = "根据id查询表单字段")
    public R<FormFieldConfig> fieldGetById(@PathVariable("fieldId") Integer id) {
        FormFieldConfig formFieldConfig = formFieldConfigService.getById(id);
        return R.ok(formFieldConfig);
    }

    @PostMapping("/field")
    @Operation(summary = "新增表单字段")
    public R fieldSave(@RequestBody @Validated FormFieldConfig dto){
        FormConfig formConfig = formConfigService.getById(dto.getFormId());
        formFieldConfigService.save(dto);
        Robot robot = robotService.getDefaultRobot();
        if (formConfig.getFormName().contains("tickets_params")
                && formConfig.getFormName().contains(robot.getRobotModel())) {
            formConfigService.syncFormMoal(formConfig.getFormName());
        }
        return R.ok();
    }

    @PutMapping("/field")
    @Operation(summary = "修改表单字段")
    public R fieldUpdateById(@RequestBody @Validated FormFieldConfig dto) {
        boolean isSuccess = formFieldConfigService.updateById(dto);
        FormConfig formConfig = formConfigService.getById(dto.getFormId());
        Robot robot = robotService.getDefaultRobot();
        if (formConfig.getFormName().contains("tickets_params")
                && formConfig.getFormName().contains(robot.getRobotModel())) {
            formConfigService.syncFormMoal(formConfig.getFormName());
        }
        return R.ok(isSuccess);
    }

    @DeleteMapping("/field")
    @Operation(summary = "根据id删除表单字段")
    public R fieldRemoveById(@RequestBody Integer[] ids) {
        return R.ok(formFieldConfigService.removeBatchByIds(CollUtil.toList(ids)));
    }


    @GetMapping("/modal/{formName}")
    @Operation(summary = "获取表单对话框内容")
    public R<FormConfigModalVo> getFormModal(@PathVariable("formName") String formName) {
        FormConfigModalVo formModal = formConfigService.getFormModal(formName);
        if (formModal == null){
            return R.failed( "表单不存在");
        }
        return R.ok(formModal);
    }


    @PostMapping("/modal/submit")
    @Operation(summary = "提交表单对话框内容")
    public R<String> submit(@RequestBody FormConfigModalVo dto){
        log.info("form:{}",dto);
        String result = formConfigService.submitFormModal(dto);
        return R.ok(result);
    }



}
